package com.xyz.messagehelper.utils

import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.telephony.SmsManager
import com.xyz.messagehelper.bean.ConstantValue.SMS_DELIVERED_ACTION
import com.xyz.messagehelper.bean.ConstantValue.SMS_SEND_ACTIOIN
import com.xyz.messagehelper.bean.MessageInfo
import android.annotation.SuppressLint
import android.net.Uri
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import java.io.File
import android.support.v4.content.FileProvider
import android.os.Build
import com.xyz.messagehelper.BuildConfig


@SuppressLint("StaticFieldLeak")
object Utils {

    lateinit var context: Context

    fun checkRuleWithFileLineIsRight(smsRule: String, fileLines: String): Boolean {
        val smsRuleSize = smsRule.split("-").size
        val fileLinesSize = fileLines.split(",").size
        return smsRuleSize == fileLinesSize
    }

    fun parseFileLineInfo(messageRules: String, fileLinesInfo: List<String>?): MessageInfo {
        val message = StringBuilder()
        //首先替换第一个*号，防止放在第一个的*，替换出错
        messageRules.replaceFirst("*", fileLinesInfo!![1])
        val split1 = messageRules.split("*")
        for ((index, content) in split1.withIndex()) {
            println(content)
            if (index + 1 == fileLinesInfo.size) {
                message.append(content)
                continue
            }
            message.append(content).append(fileLinesInfo[index + 1])
        }
        return MessageInfo(fileLinesInfo[0], message.toString())
    }


    fun sendMessage(context: Context, strDestAddress: String, strMessage: String) {
        val smsManager = SmsManager.getDefault()
        try {

            val sentIntent = Intent(SMS_SEND_ACTIOIN)
            val sentPI = PendingIntent.getBroadcast(context, 0, sentIntent, 0)

            //deliveryIntent参数为送达后接受的广播信息PendingIntent
            val itDeliver = Intent(SMS_DELIVERED_ACTION)
            val mDeliverPI = PendingIntent.getBroadcast(context, 0, itDeliver, 0)

            if (strMessage.length > 70) {
                val divideContents = smsManager.divideMessage(strMessage)
                val sentIntents = ArrayList<PendingIntent>();
                divideContents.forEach {
                    sentIntents.add(sentPI)
                }
                smsManager.sendMultipartTextMessage(
                    strDestAddress,
                    null,
                    divideContents,
                    sentIntents,
                    null
                )
            } else {
                smsManager.sendTextMessage(strDestAddress, null, strMessage, sentPI, mDeliverPI)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun getVersionName(context: Context): String {
        val packageManager = context.packageManager
        val packageInfo = packageManager.getPackageInfo(context.packageName, 0)
        return packageInfo.versionName;
    }

    @SuppressLint("SimpleDateFormat")
    fun getDate(): String {
        return SimpleDateFormat("yyyy-MM-dd").format(Date())
    }

    @SuppressLint("SimpleDateFormat")
    fun getTime(): String {
        return SimpleDateFormat("HH:mm:ss").format(Date())
    }


    fun getStringWithNumLength(str: String): Int {
        val toByteArray = str.toByteArray()
        var count = 0
        toByteArray.forEach {
            if (it in 48..57) {//数字的ASCII码为48--57
                count++;
            }
        }
        return count
    }




    fun openAndroidFile(context:Context, file: File) {
        val intent = Intent(Intent.ACTION_VIEW)
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
            val contentUri = FileProvider.getUriForFile(
                context,
                BuildConfig.APPLICATION_ID + ".fileProvider", file
            )
            intent.setDataAndType(contentUri, "text/plain")
        } else {
            intent.setDataAndType(Uri.fromFile(file), "text/plain")
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        context.startActivity(intent)
    }
}